﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
using Yoozoo.Framework.Core;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Modules.Chat
{
    public class EmojiCreator : Singleton<EmojiCreator>
    {
        private const string EmojiPath = "Assets/ResourcesAssets/UI/GUI/Emoji64.spriteatlas";
        private Dictionary<string, Sprite> spritesDic;
        private ResLoader loader;
        private GameObject prefab;
        private SpriteAtlas emojiAtlas;
        private bool isInit = false;
        public Sprite GetEmoji(string key)
        {
            Debug.Assert(isInit, "EmojiCreator must be Init");
            Sprite sp;
            if (spritesDic.TryGetValue(key, out sp))
            {
                return sp;
            }
            return null;
        }
        public bool HasEmoji(string key)
        {
            Debug.Assert(isInit, "EmojiCreator must be Init");
            return spritesDic.ContainsKey(key);
        }

        public override void Dispose()
        {
            this.loader.Recycle2Cache();
            this.loader = null;
            spritesDic.Clear();
            spritesDic = null;
            isInit = false;
            base.Dispose();
        }
        public void Init()
        {
            if (isInit)
            {
                return;
            }
            if (Application.isEditor ) //&& !UnityEditor.EditorApplication.isPlaying
            {
#if UNITY_EDITOR
                SpriteAtlas spriteAtlas = UnityEditor.AssetDatabase.LoadAssetAtPath<SpriteAtlas>(EmojiPath);
                initSpriteDic(spriteAtlas);
#endif
            }
            else
            {
                if (this.loader == null)
                {
                    this.loader = ResLoader.Alloc();
                }
                this.loader.Add2Load(EmojiPath,(success, name, asset) =>
                {
                    if (!success)
                        return;
                    var spriteAtlas = asset as SpriteAtlas;
                    initSpriteDic(spriteAtlas);
                });
                this.loader.Load();
            }
            
          
        }

        private void initSpriteDic(SpriteAtlas spriteAtlas)
        {
            if (spriteAtlas)
            {
                Sprite[] sprites = new Sprite[spriteAtlas.spriteCount];
                spriteAtlas.GetSprites(sprites);
                spritesDic = new Dictionary<string, Sprite>(spriteAtlas.spriteCount);
                for (int i = 0; i < spriteAtlas.spriteCount; i++)
                {
                    var sp = sprites[i];
                    spritesDic.Add(sp.name.Replace("(Clone)",""),sp);
                }

                isInit = true;
            }
            else
            {
                Debug.LogWarning("加载SpriteAtalas 报错");
            }
           
        }
    }
}
